<template>
  <div class="container">
    <div class="question-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>{{
              $route.query.id ? "试题修改" : "试题录入"
            }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div>
          <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <el-form-item label="学科" prop="subjectID">
              <el-select
                v-model="form.subjectID"
                placeholder="请选择"
                id="el-select"
                @change="hSubjectChange"
              >
                <el-option
                  v-for="item in subject"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录" prop="catalogID">
              <el-select v-model="form.catalogID" placeholder="请选择">
                <el-option
                  v-for="item in catalog"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="form.enterpriseID" placeholder="请选择">
                <el-option
                  v-for="item in enterprise"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="province">
              <el-select
                style="width: 190px; margin-right: 10px"
                v-model="form.province"
                @change="handleCity"
                clearable
              >
                <el-option
                  v-for="item in provinceList"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <el-select
                style="width: 200px"
                v-model="form.city"
                @change="handleCity"
                clearable
              >
                <el-option
                  v-for="item in cityList"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方向" prop="direction">
              <el-select v-model="form.direction" placeholder="请选择">
                <el-option
                  v-for="item in direction"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型">
              <el-radio-group v-model="form.questionType">
                <el-radio
                  v-for="item in questionType"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度">
              <el-radio-group v-model="form.difficulty">
                <el-radio
                  v-for="item in difficulty"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <!-- 题干 -->
            <el-form-item label="题干" prop="question" ref="formItemQuestion">
              <!--
            由于quill-editor不是el中的表单元素，所以无法像el-input一样，
            失去焦点时，立即进行校验
          -->
              <quill-editor
                v-model="form.question"
                :options="editorOption"
                @blur="hBlurQuestion"
              ></quill-editor>
            </el-form-item>
            <!-- 选项 -->
            <!-- 单选 -->
            <el-form-item
              label="选项"
              v-if="form.questionType === 1 || form.questionType === 2"
            >
              <el-radio-group
                v-model="form.optionAnds"
                class="shuiping"
                v-if="form.questionType === 1"
              >
                <el-radio
                  v-for="item in radioOptions"
                  :key="item.code"
                  :label="item.code"
                  class="jiange"
                  >{{ item.code }}
                  <el-input v-model="item.title"></el-input>
                  <el-upload
                    class="avatar-uploader upPic"
                    action="#"
                    :show-file-list="false"
                    :before-upload="
                      (file) => {
                        beforeAvatarUpload(file, item);
                      }
                    "
                  >
                    <img v-if="item.img" :src="item.img" class="avatar" />
                    <i v-else class="imgPreview">上传图片</i>
                    <i
                      class="el-icon-circle-close"
                      @click.stop="hClearImg(item)"
                    ></i>
                  </el-upload>
                </el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group
                v-model="form.optionsAnds"
                class="shuiping"
                v-if="form.questionType === 2"
              >
                <el-checkbox
                  v-for="item in checkboxOptions"
                  :key="item.code"
                  :label="item.code"
                  class="jiange"
                  >{{ item.code }}
                  <el-input v-model="item.title"></el-input>
                  <el-upload
                    class="avatar-uploader upPic"
                    action="#"
                    :show-file-list="false"
                    :before-upload="
                      (file) => {
                        beforeAvatarUpload(file, item);
                      }
                    "
                  >
                    <img v-if="item.img" :src="item.img" class="avatar" />
                    <i v-else class="imgPreview">上传图片</i>
                    <i
                      class="el-icon-circle-close"
                      @click.stop="hClearImg(item)"
                    ></i>
                  </el-upload>
                </el-checkbox>
              </el-checkbox-group>
              <el-button
                type="danger"
                @click="addCheckbox"
                class="btn"
                :disabled="form.questionType === 1"
                >+增加选项与答案</el-button
              >
            </el-form-item>
            <!-- 解析视频 -->
            <el-form-item label="解析视频">
              <el-input class="input" v-model="form.videoURL"></el-input>
            </el-form-item>
            <!-- 答案解析 -->
            <el-form-item label="答案解析" prop="answer" ref="formItemAnswer">
              <!--
            由于quill-editor不是el中的表单元素，所以无法像el-input一样，
            失去焦点时，立即进行校验
          -->
              <quill-editor
                :options="editorOption"
                v-model="form.answer"
                @blur="hBlurAnswer"
              ></quill-editor>
            </el-form-item>
            <!-- 题目备注 -->
            <el-form-item label="题目备注" prop="desc">
              <el-input
                type="textarea"
                v-model="form.remarks"
                class="activity"
              ></el-input>
            </el-form-item>
            <!-- 试题标签 -->
            <el-form-item label="标签" class="el-col">
              <el-select v-model="form.tags" placeholder="请选择" multiple>
                <el-option
                  v-for="item in tags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 提交按钮 -->
            <el-form-item>
              <el-button
                type="success"
                @click="hUpdateQuestion"
                v-if="$route.query.id"
                >确认修改</el-button
              >
              <el-button type="primary" @click="hAddQuestion" v-else
                >确认录入
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import hljs from 'highlight.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { simple as getSubject } from '../../api/hmmm/subjects'
import { simple as getCatalog } from '../../api/hmmm/directorys'
import { list as getCompanysList } from '../../api/hmmm/companys'
import { add as addQuestios, detail as getDetail, update as updateQuestion } from '../../api/hmmm/questions'
import { provinces as getProvinces, citys as getCitys } from '@/api/hmmm/citys.js'
import { difficulty, questionType, direction } from '../../api/hmmm/constants'
import { simple as getTags } from '../../api/hmmm/tags'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      editorOption: {
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image'],
            [{ direction: 'rtl' }]
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
          }
        }
      },
      // 表单验证规则
      rules: {
        subjectID: { required: true, message: '请选择学科', trigger: 'change' },
        catalogID: { required: true, message: '请选择目录', trigger: 'change' },
        enterpriseID: { required: true, message: '请选择企业', trigger: 'change' },
        province: { required: true, message: '请选择地区', trigger: 'change' },
        city: { required: true, message: '请选择城市', trigger: 'change' },
        direction: { required: true, message: '请选择方向', trigger: 'change' },
        question: { required: true, message: '请输入题干', trigger: 'blur' },
        answer: { required: true, message: '请输入答案解析', trigger: 'blur' }
      },
      form: {
        subjectID: null, // 学科id
        catalogID: null, // 目录id
        enterpriseID: null, // 企业id
        province: null, // 省份
        city: null, // 城市
        questionType: 1, // 试题类型
        difficulty: 1, // 难度
        direction: null, // 方向
        question: null, // 题干
        videoURL: '', // 解析视频
        answer: null, // 答案解析
        remarks: null, // 题目备注
        tags: [], // 试题标签
        optionAnds: '', // 单选选项
        optionsAnds: [] // 多选选项
      },
      subject: [], // 学科列表
      catalog: [], // 目录列表
      enterprise: [], // 企业列表
      provAndCity: {
        // 城市
        province: '',
        city: ''
      },
      provinceList: [], // 省列表
      cityList: [], // 城市列表
      difficulty, // 难度
      questionType, // 试题类型
      direction, // 方向
      tags: [], // 标签列表
      radioOptions: [
        // 单选选项
        {
          code: 'A',
          title: '选项A',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '选项B',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '选项C',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '选项D',
          img: '',
          isRight: false
        }
      ],
      checkboxOptions: [
        // 多选选项
        {
          code: 'A',
          title: '选项A',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '选项B',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '选项C',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '选项D',
          img: '',
          isRight: false
        }
      ],
      imageUrl: '' // 图片地址
    }
  },
  methods: {
    buildParams () {
      const {
        subjectID, // 学科id
        catalogID, // 目录id
        enterpriseID, // 企业id
        province, // 省份
        city, // 城市
        questionType, // 试题类型
        difficulty, // 难度
        direction, // 方向
        question, // 题干
        videoURL, // 解析视频
        answer, // 答案解析
        remarks, // 题目备注
        tags // 试题标签
      } = this.form
      const params = {
        subjectID, // 学科id
        catalogID, // 目录id
        enterpriseID, // 企业id
        province, // 省份
        city, // 城市
        questionType: questionType + '', // 试题类型
        difficulty: difficulty + '', // 难度
        direction, // 方向
        question, // 题干
        videoURL: videoURL + '', // 解析视频
        answer, // 答案解析
        remarks, // 题目备注
        tags: tags + '' // 试题标签
      }
      // 单选
      if (questionType === 1) {
        params.options = this.radioOptions.map(item => {
          return {
            code: item.code,
            title: item.title,
            img: item.img,
            isRight: this.form.optionAnds === item.code
          }
        })
      } else if (questionType === 2) {
        // 多选
        params.options = this.radioOptions.map(item => {
          return {
            code: item.code,
            title: item.title,
            img: item.img,
            isRight: this.form.optionsAnds.includes(item.code)
          }
        })
      } else if (questionType === 3) {
        params.options = []
      }
      return params
    },
    // 添加题库
    async doAddQuestion () {
      const params = this.buildParams()
      try {
        const res = await addQuestios(params)
        console.log(res)
        this.$message.success('添加成功')
        this.$router.push('list')
      } catch (err) {
        console.log(err)
        this.$message.error('添加失败')
      }
    },
    hAddQuestion () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.doAddQuestion()
        }
      })
    },
    // 修改题库
    async doUpdateQuestion () {
      const params = this.buildParams()
      params.id = Number(this.$route.query.id)
      try {
        const res = await updateQuestion(params)
        console.log(res)
        this.$message.success('修改成功')
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$message.error('修改失败')
      }
    },
    hUpdateQuestion () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.doUpdateQuestion()
        }
      })
    },
    // 获取学科列表
    async doGetSubject () {
      try {
        const res = await getSubject()
        console.log(res)
        this.subject = res.data
        const res1 = await getCatalog()
        this.catalog = res1.data
        const res2 = await getTags()
        this.tags = res2.data
      } catch (err) {
        console.log(err)
      }
      //   // 如果是编辑，则获取二级目录
      if (this.form.subjectID) {
        const params = {
          subjectID: this.form.subjectID
        }
        try {
          const res = await getCatalog(params)
          console.log('二级目录', res)
          this.catalog = res.data
        } catch (err) {
          console.log(err)
        }
      }
    },

    // 学科更改，获取二级目录,获取标签
    async hSubjectChange (val) {
      const params = {
        subjectID: val
      }
      try {
        const res = await getCatalog(params)
        console.log(res)
        this.catalog = res.data
      } catch (err) {
        console.log(err)
      }
      try {
        const res = await getTags(params)
        console.log(res)
        this.tags = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取企业列表
    async doGetCompanysList () {
      try {
        const res = await getCompanysList()
        console.log(res)
        this.enterprise = res.data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取省
    getCityDat () {
      this.provinceList = getProvinces()
      if (this.provAndCity.province) {
        this.cityList = getCitys(this.provAndCity.province)
      }
    },
    // 选省获取到市
    handleCity (e) {
      this.cityList = getCitys(e)
    },
    // 添加多选选项
    addCheckbox () {
      const curCode = String.fromCharCode(this.checkboxOptions.length + 65)
      this.checkboxOptions.push({
        code: curCode,
        title: '选项' + curCode,
        img: '',
        isRight: false
      })
    },
    // 试题图片上传前的文件校验
    beforeAvatarUpload (file, item) {
      console.log(item)
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      if (isJPG && isLt2M) {
        item.img = URL.createObjectURL(file)
      }
      return isJPG && isLt2M
    },
    // 关闭按钮清除图片
    hClearImg (item) {
      item.img = ''
    },
    // 富文本框失去了焦点(题干)
    hBlurQuestion () {
      console.log('富文本框失去了焦点')
      // 手动去触发对应的el-form-item项去验证
      //  this.$refs.formItem : 找到要验证的那个form-item
      //  validate是form-item对象上的方法，
      //  validate('blur'): 验证失焦的情况
      this.$refs.formItemQuestion.validate('blur')
    },
    // 富文本框失去了焦点(答案解析)
    hBlurAnswer () {
      console.log('富文本框失去了焦点')
      // 手动去触发对应的el-form-item项去验证
      //  this.$refs.formItem : 找到要验证的那个form-item
      //  validate是form-item对象上的方法，
      //  validate('blur'): 验证失焦的情况
      this.$refs.formItemAnswer.validate('blur')
    },
    // 请求试题详情
    async doGeDetail () {
      const params = {
        id: this.$route.query.id
      }
      console.log(params)
      try {
        const res = await getDetail(params)
        console.log(res)
        const {
          subjectID, // 学科id
          catalogID, // 目录id
          enterpriseID, // 企业id
          province, // 省份
          city, // 城市
          questionType, // 试题类型
          difficulty, // 难度
          direction, // 方向
          question, // 题干
          videoURL, // 解析视频
          answer, // 答案解析
          remarks, // 题目备注
          tags // 试题标签
        } = res.data
        // 回填数据
        this.form.subjectID = subjectID // 学科id
        this.form.catalogID = catalogID // 目录id
        this.form.enterpriseID = enterpriseID // 企业id
        this.form.province = province // 省份
        this.form.city = city // 城市
        this.form.questionType = Number(questionType) // 试题类型
        this.form.difficulty = Number(difficulty) // 难度
        this.form.direction = direction // 方向
        this.form.question = question // 题干
        this.form.videoURL = videoURL // 解析视频
        this.form.answer = answer // 答案解析
        this.form.remarks = remarks // 题目备注
        this.form.tags = tags.split() // 试题标签
        // 单选
        if (this.form.questionType === 1) {
          // 设置答案
          const rightItem = res.data.options.find(item => item.isRight)
          this.radioOptions = res.data.options.map(item => {
            return {
              code: item.code,
              title: item.title,
              img: item.img,
              isRight: Boolean(item.isRight)
            }
          })
          this.form.optionAnds = rightItem ? rightItem.code : ''
        } else if (this.form.questionType === 2) {
          // 多选
          this.checkboxOptions = res.data.options.map(item => {
            return {
              code: item.code,
              title: item.title,
              img: item.img,
              isRight: Boolean(item.isRight)
            }
          })
          this.form.optionsAnds = res.data.options.filter(item => item.isRight).map(item => item.code)
        }
      } catch (err) {
        console.log(err)
      }
    }
  },

  created () {
    if (this.$route.query.id) {
      // 请求试题详情
      this.doGeDetail()
    }
    this.doGetSubject()
    this.doGetCompanysList()
    this.getCityDat()
  }
}
</script>

<style scoped lang='scss'>
.box-card {
  width: 97%;
  margin-left: 20px;
  margin-top: 20px;
}
.question-container {
  padding: 0 10px;
  margin: 10px 0;
}
.el-select {
  width: 400px;
}
.el-select.el-select_1 {
  width: 200px;
}
.quill-editor {
  height: 200px;
  margin-bottom: 50px;
}
.shuiping {
  display: flex;
  flex-direction: column;
}
.jiange {
  width: 440px;
  margin-bottom: 30px;
}
.shuiping .el-input {
  margin-left: 15px;
}
.el-input {
  width: 240px;
  height: 36px;
}
.btn {
  width: 150px;
  height: 40px;
}
.activity {
  width: 400px;
  height: 95px;
}
.upPic {
  display: inline-block;
  margin-left: 10px;
  vertical-align: -webkit-baseline-middle;
}
.avatar-uploader::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  height: 60px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar {
  object-fit: cover;
  width: 120px;
  height: 60px;
}
.imgPreview {
  display: inline-block;
  font-size: 14px;
  font-style: normal;
  line-height: 50px !important;
  color: #8c939d;
  width: 120px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.el-icon-circle-close {
  position: absolute;
  top: 0;
  right: 0;
}
</style>
